﻿using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mNC.UI
{
    public partial class Frm_NC_CodeByOrder_Custom : frmBaseChild
    {
        Lamex.mNC.ucControls.ucShowPic ucShowPicList = null;
        DataTable dt_Parameter_Tools = new DataTable();
        DataTable dt_Parameter_Machine = new DataTable();
        public Frm_NC_CodeByOrder_Custom()
        {
            InitializeComponent();
        }

        private void Frm_NC_CodeByOrder_Custom_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            //开启COM扫描
            InitCom();
            dt_Parameter_Tools = Common.GetDataTable.Get_Parameter_Tools();
            dt_Parameter_Machine = Common.GetDataTable.Get_Parameter_Machine();
        }

        private void txt_OrderNumber_UcTextChanged(object sender, EventArgs e)
        {

        }
        private void txt_OrderNumber_UcTextKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                try
                {
                    gc_ShowPicture.Controls.Clear();
                    string OrderNumber = txt_OrderNumber.Text.Trim();
                    if (!string.IsNullOrEmpty(OrderNumber))
                    {
                        DataTable dt = Common.GetDataTable.Get_Part_Detailed(OrderNumber);
                        if (dt.Rows.Count > 0)
                        {
                            GetData_ComboxList(dt);//获取下拉列表                        
                        }
                    }
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                }
            }
        }
        private void cbPartNo_TextChanged(object sender, EventArgs e)
        {
            GetPic(cbDwgNo.Text, cbPartNo.Text);
        }
        private void cbDwgNo_TextChanged(object sender, EventArgs e)
        {
            GetPic(cbDwgNo.Text, cbPartNo.Text);
        }
        public void GetData_ComboxList(DataTable dt)
        {
            cbPartNo.Properties.Items.Clear();
            cbDwgNo.Properties.Items.Clear();
            foreach (DataRow row in dt.Rows)
            {
                cbPartNo.Properties.Items.Add(row["Part_No"]);
                cbDwgNo.Properties.Items.Add(row["Drawing_No"]);
            }
            cbPartNo.SelectedIndex = 0;
            cbDwgNo.SelectedIndex = 0;
        }
        public void GetPic(string strDwgNo, string strPartNo)
        {
            List<string> listPic = new List<string>();
            listPic = Common.GetShowPic.ShowPic_STD(strDwgNo, strPartNo);
            if (listPic.Count > 0)
            {
                ucShowPicList = new ucControls.ucShowPic();
                ucShowPicList.LoadImageList(listPic);
                ucShowPicList.Dock = DockStyle.Fill;
                gc_ShowPicture.Controls.Add(ucShowPicList);
            }
        }
        private void sbtnClick_Click(object sender, EventArgs e)
        {
            try
            {
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                string path = @"\\Tx-fs10\tx-fs1\LAMEX\NC\Porgram\Panel\Aluminum\";
                List<string> DWG_No_Error = new List<string>();
                List<string> Part_No_Error = new List<string>();
                if (txt_QTY.Text.Length <= 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("加工数量不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txt_QTY.Focus();
                    return;
                }
                string OrderNumber = txt_OrderNumber.Text;//订单号 "PL1912030034";//
                string PartNo = cbPartNo.Text;//物料号"3033261753"; //
                string DWGNO = cbDwgNo.Text;//图纸号
                double tolerance = txtTolerance.Text.Trim().Length > 0 ? Convert.ToDouble(txtTolerance.Text.Trim()) : 0;//公差
                decimal qty = Convert.ToDecimal(txt_QTY.Text.ToString());
                bool IsCustom = true;
                bool IsTest = false;
                DataTable dt_Cache = Common.GetCacheTable.Get_Cache_Table(PartNo, DWGNO, OrderNumber, tolerance, dt_Parameter_Tools, dt_Parameter_Machine, qty, IsCustom,IsTest);//缓存表
                                                                                                                                                                          //首先判断临时dt_Cache数据是否规范
                if (dt_Cache.Rows.Count > 0)
                {
                    bool flag_error = false;
                    for (int i = 0; i < dt_Cache.Rows.Count; i++)
                    {
                        double EXPOSED_LENTH = dt_Cache.Rows[i]["EXPOSED_LENTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["EXPOSED_LENTH"].ToString()) : 0;
                        double PROCESS_DEPTH = dt_Cache.Rows[i]["PROCESS_DEPTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["PROCESS_DEPTH"].ToString()) : 0;
                        double INITIAL_HEIGHT = dt_Cache.Rows[i]["INITIAL_HEIGHT"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["INITIAL_HEIGHT"].ToString()) : 0;
                        double FACE_HEIGHT = dt_Cache.Rows[i]["FACE_HEIGHT"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["FACE_HEIGHT"].ToString()) : 0;
                        string TOOL_NO = dt_Cache.Rows[i]["TOOL_NO"].ToString();
                        double BLADE_LENTH = dt_Cache.Rows[i]["BLADE_LENTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["BLADE_LENTH"].ToString()) : 0;
                        string sqlwhere = @"PART_NO='" + PartNo + "' and DWG_NO='" + DWGNO + "' and WORK_SURFACE='" + dt_Cache.Rows[i]["WORK_SURFACE"].ToString() + @"'
                           and FEATURE_TYPE='" + dt_Cache.Rows[i]["FEATURE_TYPE"].ToString() + "' and DEEP_CODE='" + dt_Cache.Rows[i]["DEEP_CODE"].ToString() + @"'
                           and COORD_X='" + dt_Cache.Rows[i]["COORD_X"].ToString() + "' ";
                        if (TOOL_NO.Trim().Length <= 0)
                        {
                            string update_sql = @"update [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] set ERR_INFO='无匹配刀具' where " + sqlwhere + " ";
                            BaseBuildSql.ExecuteNonQuery(update_sql);
                            flag_error = true;
                            continue;
                        }
                        if (Math.Round((EXPOSED_LENTH - 5), 2) < Math.Round((FACE_HEIGHT - PROCESS_DEPTH), 2) || Math.Round(BLADE_LENTH, 2) < Math.Round((INITIAL_HEIGHT - PROCESS_DEPTH), 2))
                        {
                            string update_sql = @"update [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] set ERR_INFO='刀具长度不足加工此特征' where " + sqlwhere + " ";
                            BaseBuildSql.ExecuteNonQuery(update_sql);
                            flag_error = true;
                            continue;
                        }

                    }
                    if (flag_error)
                    {
                        DWG_No_Error.Add(DWGNO);
                        Part_No_Error.Add(PartNo);
                        StringBuilder s1 = new StringBuilder();
                        StringBuilder s2 = new StringBuilder();
                        if (!Directory.Exists(@"D:\MESTemp"))
                            Directory.CreateDirectory(@"D:\MESTemp");
                        SaveFileDialog fileDialog = new SaveFileDialog();
                        fileDialog.Title = "导出错误列表";
                        fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                        fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                        fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
                                                                                                   //DialogResult dialogResult = fileDialog.ShowDialog(this);
                                                                                                   //if (dialogResult == DialogResult.OK)
                                                                                                   //{
                        s1.AppendFormat(@" AND PART_NO IN ('{0}')", string.Join("','", Part_No_Error.ToArray()));
                        s2.AppendFormat(@" AND DWG_NO IN ('{0}')", string.Join("','", DWG_No_Error.ToArray()));
                        string sql = @"SELECT distinct
       [DWG_NO]
      ,[PART_NO]
      ,[WORK_SURFACE]
      ,[FEATURE_TYPE]
      ,[DEEP_CODE]
      ,[COORD_X]
      ,[FEATURE_DIA]
      ,[SLOT_LENGTH]
      ,[SLOT_WIDTH]
      ,[FILLIT_RADIUS]    
      ,[ERR_INFO]
  FROM [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] where 1=1  AND ISNULL(ERR_INFO,'')!=''  " + s1.ToString() + " " + s2.ToString() + "";
                        DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql);
                        GridControl grid = new GridControl();
                        GridView view = new GridView();
                        grid.ViewCollection.Add(view);
                        grid.MainView = view;
                        view.GridControl = grid;
                        foreach (DataColumn dc in dtTemp.Columns)
                        {
                            DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                            gridColumnNumber.FieldName = dc.ColumnName;
                        }
                        grid.DataSource = dtTemp;
                        this.Controls.Add(grid);
                        grid.ForceInitialize();//强制初始化
                                               //Font font = new Font("宋体", 11, FontStyle.Bold); 
                                               //view.Appearance.HeaderPanel.Font = font;
                                               //view.Appearance.Row.Font = font;            
                        view.BestFitColumns();
                        view.OptionsView.ColumnAutoWidth = false;
                        view.OptionsView.ShowAutoFilterRow = false;
                        view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                        view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                        view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
                        //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件

                    }
                    else
                    {
                        DataView dv = new DataView(dt_Cache);
                        dv.Sort = "DWG_NO,PART_NO,QTY_TYPE,WORK_SURFACE,SUBROUTINE,TOOL_DIA,COORD_X";
                        DataTable dtResult = dv.ToTable(true, new[] { "DWG_NO", "PART_NO", "QTY_TYPE", "WORK_SURFACE", "SUBROUTINE", "TOOL_DIA" });
                        DataTable dt_QTY_TYPE = dv.ToTable(true, new[] { "QTY_TYPE", "QTY" });
                        DataTable dt_SURFACE = dv.ToTable(true, new[] { "WORK_SURFACE" });
                        DataTable dt_SUBROUTINE = dv.ToTable(true, new[] { "SUBROUTINE" });
                        //分别以MLT/MOD作为大分类,再与加工面为小类，分别生成txt
                        for (int i = 0; i < dt_QTY_TYPE.Rows.Count; i++)
                        {
                            string out_put_txt = "";
                            //1、生成MAIN_HEAD文件【MLT】
                            out_put_txt = out_put_txt + Calculate.AL_MAIN.GET_AL_MAIN_HEAD(dt_Cache.Rows[0]["DWG_NO"].ToString(),
                                dt_Cache.Rows[0]["PART_NO"].ToString(),
                                "G54",
                                dt_QTY_TYPE.Rows[i]["QTY"].ToString());

                            for (int j = 0; j < dt_SURFACE.Rows.Count; j++)
                            {
                                //2、生成FACE_HEAD文件 
                                out_put_txt = out_put_txt + Calculate.AL_FACE.GET_AL_FACE_HEAD(
                                dt_Cache.Rows[0]["DWG_NO"].ToString(),
                                dt_Cache.Rows[0]["PART_NO"].ToString(),
                                "G54",
                                dt_QTY_TYPE.Rows[i]["QTY"].ToString(),
                                dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString());
                                DataTable dtFace = dtResult.Select("QTY_TYPE='" + dt_QTY_TYPE.Rows[i]["QTY_TYPE"].ToString() + "' and WORK_SURFACE='" + dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString() + "'").CopyToDataTable();
                                for (int k = 0; k < dtFace.Rows.Count; k++)
                                {
                                    //3、生成子程序                              

                                    if (dtFace.Rows[k]["SUBROUTINE"].ToString().Length < 0)
                                        continue;
                                    string str_SUBROUTINE = dtFace.Rows[k]["SUBROUTINE"].ToString().Substring(2, 4);


                                    //得到每个子程序完整的数据
                                    string DWG_NO = dtFace.Rows[k]["DWG_NO"].ToString();
                                    string PART_NO = dtFace.Rows[k]["PART_NO"].ToString();
                                    string QTY_TYPE = dtFace.Rows[k]["QTY_TYPE"].ToString();
                                    string WORK_SURFACE = dtFace.Rows[k]["WORK_SURFACE"].ToString();
                                    string str_SUBROUTINE1 = dtFace.Rows[k]["SUBROUTINE"].ToString();
                                    string TOOL_DIA = dtFace.Rows[k]["TOOL_DIA"].ToString();
                                    string sqlWhere = @"DWG_NO='" + DWG_NO + "' and PART_NO='" + PART_NO + "' and QTY_TYPE='" + QTY_TYPE + "' and WORK_SURFACE='" + WORK_SURFACE + @"'
                                        and SUBROUTINE='" + str_SUBROUTINE1 + "' and TOOL_DIA='" + TOOL_DIA + "' ";
                                    DataTable dt_TEMP = dt_Cache.Select(sqlWhere).CopyToDataTable();
                                    //临时表升序-【必须定义好排序字段的类型，如dtNew.Columns.Add("COORD_X", typeof(double))】
                                    DataView dvTemp = new DataView(dt_TEMP);
                                    dvTemp.Sort = "DWG_NO,PART_NO,QTY_TYPE,WORK_SURFACE,SUBROUTINE,TOOL_DIA,COORD_X";
                                    dt_TEMP = dvTemp.ToTable();
                                    //【初始高度】【加工深度】
                                    string PROCESS_DEPTH = dt_TEMP.Rows[0]["PROCESS_DEPTH"].ToString();
                                    string INITIAL_HEIGHT = dt_TEMP.Rows[0]["INITIAL_HEIGHT"].ToString();

                                    switch (str_SUBROUTINE)
                                    {
                                        case "HOLE":
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                "G54",
                                                dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "",
                                                Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                                Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                                 dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                                 dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString());
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_CYCLE(dt_TEMP,
                                                INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                                PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_END();
                                            break;
                                        case "TAPP":
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_TAPP_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "",
                                                 Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                                  Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                                 dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                                 dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString());
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_AL_TAPP_CYCLE(dt_TEMP,
                                                INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                                PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_AL_TAPP_END(dt_TEMP.Rows[0]["FEATURE_TYPE"].ToString());
                                            break;
                                        case "LPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_LPCK.GET_AL_LPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_LPCK.GET_AL_LPCK_CYCLE(dt_TEMP);

                                            break;
                                        case "RPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_RPCK.GET_AL_RPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_RPCK.GET_AL_RPCK_CYCLE(dt_TEMP);


                                            break;
                                        case "CPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_CPCK.GET_AL_CPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_CPCK.GET_AL_CPCK_CYCLE(dt_TEMP);

                                            break;
                                    }
                                }
                                //4、FACE_END文件
                                out_put_txt = out_put_txt + Calculate.AL_FACE.GET_AL_FACE_END(dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString());
                            }
                            //5、生成MAIN_END文件【MLT】
                            out_put_txt = out_put_txt + Calculate.AL_MAIN.GET_AL_MAIN_END();
                            //6、生成txt    
                            string fileName = path + OrderNumber + "_" + PartNo  + "_" + dt_QTY_TYPE.Rows[i]["QTY_TYPE"].ToString();
                            FileStream fs = new FileStream(fileName + "_L.NC", FileMode.Create);
                            Common.GetTxtFile.GetTxtNodes(fs, out_put_txt);
                            //7、复制一个R.NC的txt
                            File.Copy(fileName + "_L.NC", fileName + "_R.NC", true);
                            //8、修改R.NC文件机头代码为G55
                            Common.GetTxtFile.EditTxtNodes("G54", "G55", fileName + "_R.NC");

                        }
                        DevExpress.XtraEditors.XtraMessageBox.Show("文件转换成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearData();
                    }

                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("物料【" + PartNo + "】图纸【" + DWGNO + "】特征数据不存在,请确认!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.CloseSplashScreen();

            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }

        }
        private void ClearData()
        {
            txt_OrderNumber.Text = "";
            cbPartNo.Properties.Items.Clear();
            cbDwgNo.Properties.Items.Clear();
            cbDwgNo.Text = "";
            cbPartNo.Text = "";
            txt_QTY.Text = "";
            txtTolerance.Text = "";
        }
        #region 扫描COM实现
        SerialPort serialPort1 = new SerialPort();
        SerialPort serialPort2 = new SerialPort();
        SerialPort serialPort3 = new SerialPort();
        SerialPort serialPort4 = new SerialPort();
        SerialPort serialPort5 = new SerialPort();
        SerialPort serialPort6 = new SerialPort();
        SerialPort serialPort7 = new SerialPort();
        SerialPort serialPort8 = new SerialPort();
        string COM1 = "";
        string COM2 = "";
        string COM3 = "";
        string COM4 = "";
        string COM5 = "";
        string COM6 = "";
        string COM7 = "";
        string COM8 = "";
        public string[] GetRunCom()
        {
            string[] str = SerialPort.GetPortNames();
            return str;
        }
        public void InitCom()
        {
            string[] str = GetRunCom();
            if (str == null)
            {
                return;
            }
            Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\ComSetting.ini");
            COM1 = ini.IniReadValue("COM Configuration", "COM1");
            COM2 = ini.IniReadValue("COM Configuration", "COM2");
            COM3 = ini.IniReadValue("COM Configuration", "COM3");
            COM4 = ini.IniReadValue("COM Configuration", "COM4");
            COM5 = ini.IniReadValue("COM Configuration", "COM5");
            COM6 = ini.IniReadValue("COM Configuration", "COM6");
            COM7 = ini.IniReadValue("COM Configuration", "COM7");
            COM8 = ini.IniReadValue("COM Configuration", "COM8");
            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == COM1)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(s, serialPort1);
                }
                else if (s == COM2)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(s, serialPort2);
                }
                else if (s == COM3)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(s, serialPort3);
                }
                else if (s == COM4)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(s, serialPort4);
                }
                else if (s == COM5)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(s, serialPort5);
                }
                else if (s == COM6)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(s, serialPort6);
                }
                else if (s == COM7)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(s, serialPort7);
                }
                else if (s == COM8)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(s, serialPort8);
                }

            }
            //StartTime();
            //alterTime();
        }

        public void InitSingleCom(string PortName)
        {
            string[] str = GetRunCom();

            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == PortName)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort1);
                }
                else if (s == PortName)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort2);
                }
                else if (s == PortName)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort3);
                }
                else if (s == PortName)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort4);
                }
                else if (s == PortName)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort5);
                }
                else if (s == PortName)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort6);
                }
                else if (s == PortName)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort7);
                }
                else if (s == PortName)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort8);
                }

                System.Threading.Thread.Sleep(1000);

            }
        }
        /// <summary>
        /// 实例化串行端口资源
        /// </summary>
        public void InstanceSerialPort(string comName, SerialPort serialPort)
        {


            try
            {
                //实例化串行端口
                //SerialPort serialPort = new SerialPort();
                //端口名  注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
                serialPort.PortName = comName;
                //波特率
                serialPort.BaudRate = 9600;
                //奇偶校验
                serialPort.Parity = Parity.None;
                //停止位
                serialPort.StopBits = StopBits.One;
                //数据位
                serialPort.DataBits = 8;
                //忽略null字节
                serialPort.DiscardNull = true;

                //接收事件
                serialPort.DataReceived += serialPort_DataReceived;
                //开启串口
                serialPort.Open();
                //alterTime();
            }
            catch (Exception ex)
            {
                //XtraMessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            try
            {
                ReceiveData(serialPort);
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }

        public void ReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            try
            {
                //防止数据接收不完整 线程sleep(100)
                System.Threading.Thread.Sleep(100);

                string str = serialPort.ReadExisting();
                //str = str.Replace("\r", "\r\n");
                if (str == string.Empty)
                {
                    return;
                }
                else
                {
                    txt_OrderNumber.Invoke(new Action(() => { txt_OrderNumber.Text = str.Replace("\r", "").Trim(); txt_OrderNumber.Focus(); SendKeys.Send("\r\n"); }));

                }
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }
        public void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (COM1 == serialPort1.PortName)
            {
                if (serialPort1.IsOpen != true)
                {
                    serialPort1.Close();
                    InitSingleCom(serialPort1.PortName);
                }
            }
            if (COM2 == serialPort2.PortName)
            {
                if (serialPort2.IsOpen != true)
                {
                    serialPort2.Close();
                    InitSingleCom(serialPort2.PortName);
                }
            }
            if (COM3 == serialPort3.PortName)
            {
                if (serialPort3.IsOpen != true)
                {
                    serialPort3.Close();
                    InitSingleCom(serialPort3.PortName);
                }
            }
            if (COM4 == serialPort4.PortName)
            {
                if (serialPort4.IsOpen != true)
                {
                    serialPort4.Close();
                    InitSingleCom(serialPort4.PortName);
                }

            }
            if (COM5 == serialPort5.PortName)
            {
                if (serialPort5.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort5.PortName);
                }
            }
            if (COM6 == serialPort6.PortName)
            {
                if (serialPort6.IsOpen != true)
                {
                    serialPort6.Close();
                    InitSingleCom(serialPort6.PortName);
                }
            }
            if (COM7 == serialPort7.PortName)
            {
                if (serialPort7.IsOpen != true)
                {
                    serialPort7.Close();
                    InitSingleCom(serialPort7.PortName);
                }
            }
            if (COM8 == serialPort8.PortName)
            {
                if (serialPort8.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort8.PortName);
                }
            }
        }

        public void CloseReceiveData()
        {
            serialPort1.Dispose();
            serialPort2.Dispose();
            serialPort3.Dispose();
            serialPort4.Dispose();
            serialPort5.Dispose();
            serialPort6.Dispose();
            serialPort7.Dispose();
            serialPort8.Dispose();
            serialPort1.Close();
            serialPort2.Close();
            serialPort3.Close();
            serialPort4.Close();
            serialPort5.Close();
            serialPort6.Close();
            serialPort7.Close();
            serialPort8.Close();

        }
        #endregion

        private void Frm_NC_CodeByOrder_Custom_Resize(object sender, EventArgs e)
        {
            panelControl4.Width = panelControl3.Width;

            groupControl1.Height = panelControl3.Height / 2;
            groupControl2.Height = panelControl3.Height / 2;
            groupControl3.Height = panelControl3.Height / 2;
            groupControl4.Height = panelControl3.Height / 2;
        }
    }
}
